package com.zhuhjay.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全框架的配置文件
 * @author ZhuHJay
 * @date 2022/4/4 14:12
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启全局方法注解安全校验
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /** 加密 **/
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     * 取消对静态资源的拦截
     */
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(
                "/js/**",
                "/css/**",
                "/img/**",
                "/plugins/**",
                "/template/**",
                "login.html"
        );//对于这些静态文件，忽略拦截
    }

    /**
     * 对spring security 的配置
     * 拦截url
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 配置<iframe>页面正常访问
        http.headers().frameOptions().sameOrigin();
        http.formLogin() //使用表单登录
                // 指向登录页面，或者是路由(注意/)
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/pages/main.html")
                .and()
                //授权操作
                .authorizeRequests()
                // permitAll 任何身份均可以访问
                .antMatchers("/login.html").permitAll()
                .anyRequest()  // 任何请求
                .authenticated() // 需要身份认证
                .and()
                .csrf().disable(); // 关闭跨站请求防护

        http.logout()
                // 清空session数据
                .invalidateHttpSession(true)
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html");
    }

}
